package cool.webstudy.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cool.webstudy.admin.constant.enums.rescode.AttackRecordResCodeEnum;
import cool.webstudy.admin.constant.enums.rescode.UserResCodeEnum;
import cool.webstudy.admin.exception.BusinessException;
import cool.webstudy.admin.mapper.attackrecord.AttackRecordMapper;
import cool.webstudy.admin.model.dto.attackrecord.CreateAttackRecordDTO;
import cool.webstudy.admin.model.dto.attackrecord.PaginationQueryAttackRecordListDTO;
import cool.webstudy.admin.model.dto.user.UserDetailInfoDTO;
import cool.webstudy.admin.model.po.attackrecord.AttackRecordPO;
import cool.webstudy.admin.model.vo.attackrecord.PaginationQueryAttackRecordListVO;
import cool.webstudy.admin.model.vo.attackrecord.QueryTeamAttackRecordListVO;
import cool.webstudy.admin.model.vo.team.user.QueryTeamUserDetailInfoVO;
import cool.webstudy.admin.service.*;
import cool.webstudy.admin.utils.UserDetailUtil;
import cool.webstudy.common.utils.UUIDUtil;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @author 莫振双
 * @date 2025/4/6 16:53
 * @description: 攻击记录服务实现类
 */
@Service
public class AttackRecordServiceImpl implements AttackRecordService {
    @Autowired
    private AttackRecordMapper attackRecordMapper;
    @Autowired
    private CompetitionService competitionService;
    @Autowired
    private UserService userService;
    @Autowired
    private TeamService teamService;
    @Autowired
    private TeamUserService teamUserService;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void createAttackRecord(CreateAttackRecordDTO dto) {
        UserDetailInfoDTO userDetailInfoDTO = UserDetailUtil.getUserDetailInfo();
        AttackRecordPO attackRecordPO = new AttackRecordPO();
        attackRecordPO.setUnCode(UUIDUtil.getUUID());
        attackRecordPO.setCompUnCode(dto.getCompUnCode());
        attackRecordPO.setAttackerTeamUnCode(dto.getAttackerTeamUnCode());
        attackRecordPO.setAttackerTeamScore(dto.getAttackerTeamScore());
        attackRecordPO.setTeamUnCodeUnderAttack(dto.getTeamUnCodeUnderAttack());
        attackRecordPO.setTeamUnderAttackScore(dto.getTeamUnUnderAttackScore());
        attackRecordPO.setFlag(dto.getFlag());
        attackRecordPO.setScores(dto.getScores());
        attackRecordPO.setCreateBy(userDetailInfoDTO.getUnCode());
        attackRecordPO.setUpdateBy(userDetailInfoDTO.getUnCode());
        attackRecordPO.setCreateTime(new Date());
        attackRecordPO.setUpdateTime(new Date());
        try {
            attackRecordMapper.insert(attackRecordPO);
        } catch (Exception e) {
            throw new BusinessException(AttackRecordResCodeEnum.RC_ATTACK_RECORD_INSERT_FAILED);
        }
    }

    @Override
    public Boolean isExistRecord(String compUnCode, String teamUnCode, String flag) {
        LambdaQueryWrapper<AttackRecordPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(AttackRecordPO::getCompUnCode, compUnCode)
                .eq(AttackRecordPO::getAttackerTeamUnCode, teamUnCode)
                .eq(AttackRecordPO::getFlag, flag);
        try {
            return attackRecordMapper.selectOne(queryWrapper) != null;
        } catch (Exception e) {
            throw new BusinessException(AttackRecordResCodeEnum.RC_ERROR_ATTACK_RECORD_QUERY);
        }
    }

    @Override
    public Page<PaginationQueryAttackRecordListVO> paginationQueryAttackRecordList(PaginationQueryAttackRecordListDTO dto) {
        Page<PaginationQueryAttackRecordListVO> paginationQueryAttackRecordListVOPage = new Page<>();
        Page<AttackRecordPO> page = new Page<>(dto.getCurrent(), dto.getPageSize());
        //赛事业务主键列表
        List<String> compUnCodeList = List.of();
        //赛事信息map
        Map<String, String> competitionUnCodeNameMap = Map.of();
        //如果模糊查询条件不为空，则查询赛事信息map
        if (StringUtils.isNotBlank(dto.getContext())) {
            competitionUnCodeNameMap = competitionService.queryCompetitionUnCodeNameMapByContext(dto.getContext());
            if (!competitionUnCodeNameMap.isEmpty()) {
                compUnCodeList = new ArrayList<>(competitionUnCodeNameMap.keySet());
            }
        } else {
            competitionUnCodeNameMap = competitionService.queryCompetitionRoughInfoMap();
            if (!competitionUnCodeNameMap.isEmpty()) {
                compUnCodeList = new ArrayList<>(competitionUnCodeNameMap.keySet());
            }
        }
        LambdaQueryWrapper<AttackRecordPO> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Objects.nonNull(dto.getCompUnCode()), AttackRecordPO::getCompUnCode, dto.getCompUnCode())
                .or().in(!compUnCodeList.isEmpty(), AttackRecordPO::getCompUnCode, compUnCodeList);
        try {
            Page<AttackRecordPO> attackRecordPOPage = attackRecordMapper.selectPage(page, queryWrapper);
            if (Objects.nonNull(attackRecordPOPage)) {
                //查询用户信息map
                Map<String, String> userUnCodeNameMap = userService.queryUserUnCodeNameMap();
                //查询队伍信息map
                Map<String, String> teamUnCodeNameMap = teamService.queryTeamRoughInfoMap();
                List<PaginationQueryAttackRecordListVO> paginationQueryAttackRecordListVOList = new ArrayList<>();
                for (AttackRecordPO attackRecordPO : attackRecordPOPage.getRecords()) {
                    PaginationQueryAttackRecordListVO vo = new PaginationQueryAttackRecordListVO();
                    vo.setUnCode(attackRecordPO.getUnCode());
                    vo.setCompName(competitionUnCodeNameMap.get(attackRecordPO.getCompUnCode()));
                    //翻译攻击队伍名称
                    vo.setAttackerTeamName(teamUnCodeNameMap.get(attackRecordPO.getAttackerTeamUnCode()));
                    vo.setAttackerTeamScore(attackRecordPO.getAttackerTeamScore());
                    //翻译被攻击队伍名称
                    vo.setTeamUnderAttackName(teamUnCodeNameMap.get(attackRecordPO.getTeamUnCodeUnderAttack()));
                    vo.setTeamUnderAttackScore(attackRecordPO.getTeamUnderAttackScore());
                    vo.setScores(attackRecordPO.getScores());
                    //翻译攻击者姓名
                    vo.setCreateBy(userUnCodeNameMap.get(attackRecordPO.getCreateBy()));
                    vo.setCreateTime(attackRecordPO.getCreateTime());
                    paginationQueryAttackRecordListVOList.add(vo);
                }
                paginationQueryAttackRecordListVOPage.setRecords(paginationQueryAttackRecordListVOList);
                paginationQueryAttackRecordListVOPage.setCurrent(attackRecordPOPage.getCurrent());
                paginationQueryAttackRecordListVOPage.setPages(attackRecordPOPage.getPages());
                paginationQueryAttackRecordListVOPage.setSize(attackRecordPOPage.getSize());
                paginationQueryAttackRecordListVOPage.setTotal(attackRecordPOPage.getTotal());
                return paginationQueryAttackRecordListVOPage;
            }
            return paginationQueryAttackRecordListVOPage;
        } catch (Exception e) {
            throw new BusinessException(AttackRecordResCodeEnum.RC_ERROR_ATTACK_RECORD_QUERY);
        }
    }

    @Override
    public List<QueryTeamAttackRecordListVO> queryTeamAttackRecordListByCompUnCode(String compUnCode) {
        if (StringUtils.isBlank(compUnCode)) {
            return List.of();
        }
        //查询当前登录用户所属队伍
        UserDetailInfoDTO userDetailInfoDTO = UserDetailUtil.getUserDetailInfo();
        if ("system".equals(userDetailInfoDTO.getAccount())) {
            throw new BusinessException(UserResCodeEnum.RC_ERROR_NOT_LOGIN);
        }
        QueryTeamUserDetailInfoVO queryTeamUserDetailInfoVO = teamUserService.queryTeamUserDetailInfoByUserUnCode(userDetailInfoDTO.getUnCode());
        try {

            List<AttackRecordPO> attackRecordPOList = attackRecordMapper.selectList(new LambdaQueryWrapper<AttackRecordPO>()
                    .eq(AttackRecordPO::getCompUnCode, compUnCode)
                    .eq(AttackRecordPO::getAttackerTeamUnCode, queryTeamUserDetailInfoVO.getTeamUnCode()));
            if (!attackRecordPOList.isEmpty()) {
                Map<String, String> teamUnCodeNameMap = teamService.queryTeamRoughInfoMap();
                Map<String, String> userUnCodeNameMap = userService.queryUserUnCodeNameMap();
                List<QueryTeamAttackRecordListVO> queryTeamAttackRecordListVOList = new ArrayList<>();
                for (AttackRecordPO attackRecordPO : attackRecordPOList) {
                    QueryTeamAttackRecordListVO vo = new QueryTeamAttackRecordListVO();
                    vo.setUnCode(attackRecordPO.getUnCode());
                    vo.setAttackerTeamName(teamUnCodeNameMap.get(attackRecordPO.getAttackerTeamUnCode()));
                    vo.setAttackerTeamScore(attackRecordPO.getAttackerTeamScore());
                    vo.setTeamUnderAttackName(teamUnCodeNameMap.get(attackRecordPO.getTeamUnCodeUnderAttack()));
                    vo.setTeamUnderAttackScore(attackRecordPO.getTeamUnderAttackScore());
                    vo.setScores(attackRecordPO.getScores());
                    vo.setAttackerName(userUnCodeNameMap.get(attackRecordPO.getCreateBy()));
                    vo.setAttackTime(attackRecordPO.getCreateTime());
                    queryTeamAttackRecordListVOList.add(vo);
                }
                return queryTeamAttackRecordListVOList;
            }
        } catch (Exception e) {
            throw new BusinessException(AttackRecordResCodeEnum.RC_ERROR_ATTACK_RECORD_QUERY);
        }
        return List.of();
    }
}
